package com.springboot.prac.prac03_algorithm.array;

/**
 * 数组  新增/删除/扩容
 */
public class OperateArray {
    private int[] array;
    private int size;

    public OperateArray(int capacity) {
        // 初始化数组
        this.array = new int[capacity];
        this.size = 0;
    }

    // 数组插入
    public void insert(int index, int element) {
        // 插入前判断index
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("超出数组实际元素范围");
        }

        // 如果数组达到数组容量上限，则对数组进行扩容
        if (size >= array.length) {
            resize();
        }

        // 从右往左循环
        for (int i = size - 1; i >= index; i--) {
            array[i + 1] = array[i];
        }

        array[index] = element;
        size++;
    }

    // 删除元素
    public int delete(int index) {
        // 删除前判断index
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("超出数组实际元素范围");
        }

        int deleteElement = array[index];

        for (int i = index; i < size - 1; i++) {
            array[i] = array[i + 1];
        }

        size--;
        return deleteElement;
    }

    // 扩容
    public void resize() {
        int[] arrayNew = new int[array.length * 2];
        System.arraycopy(array, 0, arrayNew, 0, array.length);
        array = arrayNew;
    }

    public void output() {
        for (int i = 0; i < size; i++) {
            System.out.println(array[i]);
        }
    }

    public static void main(String[] args) {
        OperateArray array = new OperateArray(5);
        array.insert(0, 3);
        array.insert(1, 7);
        array.insert(2, 9);
        array.insert(3, 5);
        array.insert(1, 6);
        array.insert(1, 2);
        array.insert(4, 22);

        array.delete(4);
        array.output();
    }
}